import hashlib
import json
from django.core import serializers
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.response import Response
from rest_framework.views import APIView
from hospital_model.models import ProjectModel
from reservation_model.models import ReservationOrderModel
from user_model.models import UserModel, RelationModel, AssociatedModel, ComplainModel, RelevanceModel
from user_model.serializer import RegisterSerializer, LoginSerializer, ModificationSerializer, ComplaintSerializer
from django.core.cache import cache
from utils.check import is_valid_idcard, is_phone, is_code
from utils.sms import sms_code
# from utils.user_jwt import create_token
from utils.jwt_auth import create_token
from extensions.auth import JwtQueryParamAuthentication


# 获取验证码
class AuthCodeView(APIView):
    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        if is_phone(phone):
            sms_code(phone)
            data = {
                'msg': "验证码获取成功",
                'code': 2000,
            }
            return Response(data)
        else:
            return Response('手机号有误')


# 注册
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            name = request.POST['name']
            password = request.POST['password']
            ID_card = request.POST['ID_card']
            address = request.POST['address']
            phone = request.POST['phone']
            code = request.POST['code']
            emergency_contact = request.POST['emergency_contact']
            if is_phone(phone) and is_phone(emergency_contact) and is_code(code) and is_valid_idcard(ID_card):
                if len(UserModel.objects.filter(u_phone=phone, u_IDcard=ID_card)) == 0:
                    UserModel.objects.create(u_phone=phone,
                                             u_name=name,
                                             u_password=password,
                                             u_IDcard=ID_card,
                                             u_address=address,
                                             emergency_contact=emergency_contact)
                    cache.delete(phone)
                    token = create_token({'phone': phone})
                    data = {}
                    data['name'] = name
                    data['ID_card'] = ID_card
                    data['address'] = address
                    data['emergency_contact'] = emergency_contact
                    data = {
                        'msg': '注册成功',
                        'code': 2000,
                        'data': data,
                        'token': token
                    }
                    return Response(data)
                else:
                    data = {
                        'msg': "用户已存在",
                        'code': 4000,
                    }
                    return Response(data)
            else:
                data = {
                    'msg': "请检查用户信息是否有误",
                    'code': 4000,
                }
                return Response(data)
        else:
            data = {
                'msg': "注册信息验证不通过，请检查",
                'code': 4000,
            }
            return Response(data)


# 手机号或者身份证号登录
class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        login_name = request.POST['login_name']
        password = request.POST['password']
        if len(login_name) == 11:
            if is_phone(login_name):
                user_number = UserModel.objects.filter(u_phone=login_name)
                if user_number == 0:
                    data = {
                        'msg': "没有找到此用户",
                        'code': 40000,
                    }
                    return Response(data)
                else:
                    data_lists = (json.loads(serializers.serialize('json', user_number)))[0]['fields']
                    d_password = data_lists['u_password']
                    sha_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
                    if sha_password == d_password:
                        data = {}
                        data['name'] = data_lists['u_name']
                        data['u_phone'] = data_lists['u_phone']
                        data['u_IDcard'] = data_lists['u_IDcard']
                        data['u_address'] = data_lists['u_address']
                        data['emergency_contact'] = data_lists['emergency_contact']
                        data = {
                            'msg': "登录成功",
                            'code': 2000,
                            'data': data
                        }
                        return Response(data)
                    else:
                        data = {
                            'msg': "登录失败",
                            'code': 4000,
                        }
                        return Response(data)
            else:
                data = {
                    'msg': "手机号验证不通过",
                    'code': 4000,
                }
                return Response(data)
        elif len(login_name) == 18:
            if is_valid_idcard(login_name):
                user_number = UserModel.objects.filter(u_IDcard=login_name)
                if user_number == 0:
                    data = {
                        'msg': "没有找到此用户",
                        'code': 40000,
                    }
                    return Response(data)
                else:
                    data_lists = (json.loads(serializers.serialize('json', user_number)))[0]['fields']
                    d_password = data_lists['u_password']
                    sha_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
                    if sha_password == d_password:
                        data = {}
                        data['name'] = data_lists['u_name']
                        data['u_phone'] = data_lists['u_phone']
                        data['u_IDcard'] = data_lists['u_IDcard']
                        data['u_address'] = data_lists['u_address']
                        data['emergency_contact'] = data_lists['emergency_contact']
                        data = {
                            'msg': "登录成功",
                            'code': 2000,
                            'data': data
                        }
                        return Response(data)
                    else:
                        data = {
                            'msg': "登录失败",
                            'code': 4000,
                        }
                        return Response(data)
            else:
                data = {
                    'msg': "身份证号验证不通过",
                    'code': 4000,
                }
                return Response(data)
        else:
            data = {
                'msg': "请检查输入信息是否有误",
                'code': 4000,
            }
            return Response(data)


# 验证码登录
class LoginCodeView(APIView):
    def post(self, request, *args, **kwargs):
        phone = request.POST['phone']
        code = request.POST['code']
        if is_phone(phone) and is_code(code):
            redis_code = cache.get(phone)
            if redis_code == int(code):
                details = \
                    json.loads(serializers.serialize('json', UserModel.objects.filter(u_phone=phone)))[0][
                        'fields']
                cache.delete(phone)
                token = create_token({'username': phone})
                data = {}
                data['name'] = details['u_name']
                data['u_phone'] = details['u_phone']
                data['u_IDcard'] = details['u_IDcard']
                data['u_address'] = details['u_address']
                data['emergency_contact'] = details['emergency_contact']
                data = {
                    'msg': "登录成功",
                    'code': 2000,
                    'data': data,
                    'token': token
                }
                return Response(data)
            else:
                data = {
                    'msg': "登录失败",
                    'code': 4000,

                }
                return Response(data)
        else:
            data = {
                'msg': "请检查手机号和验证码是否输入正确",
                'code': 2000,

            }
            return Response(data)


# 信息修改
class ModificationView(APIView):
    def post(self, request, *args, **kwargs):
        address = request.POST['address']
        ID_card = request.POST['ID_card']
        if is_valid_idcard(ID_card):
            users = UserModel.objects.filter(u_IDcard=ID_card)
            if users == 0:
                data = {
                    'msg': "用户地址修改失败",
                    'code': 4000
                }
                return Response(data)
            else:
                UserModel.objects.filter(u_IDcard=ID_card).update(u_address=address)
                data = {
                    'msg': "用户地址修改成功",
                    'code': 2000
                }
                return Response(data)
        else:
            data = {
                'msg': "验证不通过",
                'code': 4000
            }
            return Response(data)

# 用户注销
class UnsubscribeView(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        users = UserModel.objects.filter(u_IDcard=ID_card).all()
        if users.count() != 0:
            UserModel.objects.filter(u_IDcard=ID_card).update(u_status='1')
            data = {
                'msg': "用户删除成功",
                'code': 2000
            }
            return Response(data)
        else:
            data = {
                'msg': "用户删除失败",
                'code': 4000
            }
            return Response(data)


# 忘记密码
class ForgetPassword(APIView):
    def post(self, request, *args, **kwargs):
        id_card = request.POST['id_card']
        phone = request.POST['phone']
        code = request.POST['code']
        password = request.POST['password']
        if len(UserModel.objects.filter(u_IDcard=id_card, u_phone=phone)) == 0:
            data = {
                'msg': "用户手机号和身份证号不匹配",
                'code': 4000,
            }
            return Response(data)
        else:
            redis_code = cache.get(phone)
            if (redis_code == int(code)) and len(password) > 6:
                UserModel.objects.filter(u_phone=phone).update(
                    u_password=hashlib.sha256(password.encode("utf-8")).hexdigest())
                cache.delete(phone)
                data = {
                    'msg': "密码设置成功",
                    'code': 2000,
                }
                return Response(data)
            else:
                data = {
                    'msg': "验证码错误",
                    'code': 4000,
                }
                return Response(data)

# 关联用户
class AssociatedUserView(APIView):
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        # 关联用户姓名
        new_name = request.POST['new_name']
        # 关联用户身份证号
        new_ID_card = request.POST['new_ID_card']
        # 关联用户地址
        new_address = request.POST['new_address']
        # 关联用户关系
        new_relation = request.POST['new_relation']
        users = UserModel.objects.filter(u_IDcard=ID_card).all()
        if users.count() != 0:
            associated = AssociatedModel.objects.filter(user_id=ID_card).all()
            if associated.count() == 0:
                AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                RelationModel.objects.create(r_name=new_name, r_ID_card=new_ID_card, r_address=new_address)
                data = {
                    'msg': "用户添加成功",
                    'code': 2000
                }
                return Response(data)
            else:
                data_lists = (json.loads(serializers.serialize('json', associated)))
                id_card = []
                for data in data_lists:
                    id_card.append(data['fields']['associated_id'])
                if (new_ID_card in id_card):
                    data = {
                        'msg': "用户关系已存在",
                        'code': 4000
                    }
                    return Response(data)
                else:
                    AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                    data = {
                        'msg': "用户关系添加成功",
                        'code': 2000
                    }
                    return Response(data)
        else:
            associated = AssociatedModel.objects.filter(user_id=ID_card).all()
            if associated.count() == 0:
                AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                RelationModel.objects.create(r_name=new_name, r_ID_card=new_ID_card, r_address=new_address)
                data = {
                    'msg': "用户添加成功",
                    'code': 2000
                }
                return Response(data)
            else:
                data_lists = (json.loads(serializers.serialize('json', associated)))
                id_card = []
                for data in data_lists:
                    id_card.append(data['fields']['associated_id'])
                if (new_ID_card in id_card):
                    data = {
                        'msg': "用户关系已存在",
                        'code': 4000
                    }
                    return Response(data)
                else:
                    AssociatedModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated=new_relation)
                    data = {
                        'msg': "用户关系添加成功",
                        'code': 2000
                    }
                    return Response(data)


# 建立关联用户
class SetRelevance(APIView):
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        # 关联用户姓名
        new_name = request.POST['new_name']
        # 关联用户身份证号
        new_ID_card = request.POST['new_ID_card']
        # 关联用户地址
        new_address = request.POST['new_address']
        # 关联用户关系
        new_relation = request.POST['new_relation']
        # print(is_valid_idcard(ID_card) and is_valid_idcard(new_ID_card))
        if is_valid_idcard(ID_card) and is_valid_idcard(new_ID_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card, associated_id=new_ID_card, r_status=0)
            if len(is_null) == 0:
                RelevanceModel.objects.create(user_id=ID_card, associated_id=new_ID_card, associated_name=new_name,
                                              associated=new_relation, r_address=new_address)
                users = json.loads(serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card,
                                                                                               associated_id=new_ID_card)))
                if len(users) == 0:
                    data = {
                        'msg': "用户关系添加失败",
                        'code': 40001
                    }
                    return Response(data)
                else:
                    da = users[0]['fields']
                    data = {
                        'msg': "用户关系关联成功",
                        'code': 20001,
                        'data': da
                    }
                    return Response(data)
            else:
                RelevanceModel.objects.filter(user_id=ID_card, associated_id=new_ID_card, r_status=1).update(
                    associated_name=new_name, associated=new_relation, r_address=new_address, r_status=0)
                users = json.loads(serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card,
                                                                                               associated_id=new_ID_card)))
                if len(users) == 0:
                    data = {
                        'msg': "用户关系添加失败",
                        'code': 40001
                    }
                    return Response(data)
                else:
                    da = users[0]['fields']
                    data = {
                        'msg': "用户关系关联成功",
                        'code': 20001,
                        'data': da
                    }
                    return Response(data)
        else:
            data = {
                'msg': "身份证号验证不通过",
                'code': 40002
            }
            return Response(data)


# 查询用户关系
class QueryRelevance(APIView):
    # authentication_classes = []
    # authentication_classes = [JwtQueryParamAuthentication, ]
    def post(self, request, *args, **kwargs):
        # 用户身份证号
        ID_card = request.POST['ID_card']
        datas = []
        if is_valid_idcard(ID_card):
            is_null = json.loads(
                serializers.serialize('json', RelevanceModel.objects.filter(user_id=ID_card, r_status=0)))
            if len(is_null) == 0:
                data = {
                    'msg': "该用户还没有关联用户",
                    'code': 40002
                }
                return Response(data)
            else:
                for a in is_null:
                    datas.append(a['fields'])
                data = {
                    'msg': "获取成功",
                    'code': 20000,
                    'data': datas
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证号验证不通过",
                'code': 40002
            }
            return Response(data)


# 修改用户关系
class AmendRelevance(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        relevance_card = request.POST['relevance_card']
        associated = request.POST['associated']
        if is_valid_idcard(ID_card) and is_valid_idcard(relevance_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card,associated_id=relevance_card).update(associated=associated)
            if int(is_null) != 0:
                data = {
                    'msg': "修改成功",
                    'code': 20002,
                }
                return Response(data)
            else:
                data = {
                    'msg': "修改失败",
                    'code': 40002,
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证验证不通过",
                'code': 400020,
            }
            return Response(data)


# 解除用户关系
class DelRelevance(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']
        relevance_card = request.POST['relevance_card']
        if is_valid_idcard(ID_card) and is_valid_idcard(relevance_card):
            is_null = RelevanceModel.objects.filter(user_id=ID_card, associated_id=relevance_card).update(r_status=1)
            if int(is_null) != 0:
                data = {
                    'msg': "解除关联成功",
                    'code': 20002,
                }
                return Response(data)
            else:
                data = {
                    'msg': "解除关联失败",
                    'code': 40002,
                }
                return Response(data)
        else:
            data = {
                'msg': "身份证验证不通过",
                'code': 400020,
            }
            return Response(data)
